import { DataTypes, Model } from 'sequelize';
import sequelize from '../db';

class Permission extends Model {
  public id!: string;
  public resource!: string;
  public action!: string;
  public description?: string;
  public module!: string; // 权限所属模块
  public moduleName?: string; // 模块中文名称
  public isSystem!: boolean; // 是否为系统权限
  public sortOrder!: number; // 排序序号
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;

  getIdentifier(): string {
    return `${this.resource}:${this.action}`;
  }
}

Permission.init(
  {
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
    },
    resource: {
      type: DataTypes.STRING(100),
      allowNull: false,
    },
    action: {
      type: DataTypes.STRING(50),
      allowNull: false,
    },
    description: {
      type: DataTypes.TEXT,
      allowNull: true,
    },
    module: {
      type: DataTypes.STRING(100),
      allowNull: false,
      defaultValue: 'system',
    },
    moduleName: {
      type: DataTypes.STRING(100),
      allowNull: true,
      field: 'module_name',
    },
    isSystem: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false,
      field: 'is_system',
    },
    sortOrder: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      field: 'sort_order',
    },
  },
  {
    sequelize,
    tableName: 'permissions',
    underscored: true,
    timestamps: true,
  },
);

export default Permission;

